//
//  API.swift
//  API
//
//  Created by ET|冰琳 on 2017/3/23.
//  Copyright © 2017年 IB. All rights reserved.
//

import UIKit
import Alamofire
import ReactiveSwift
import MappingAce


/// 工程通用逻辑
struct API {
    
    static func request(
        _ url: URLConvertible,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        encoding: ParameterEncoding = URLEncoding.default,
        headers: HTTPHeaders? = nil)
        -> DataRequest
    {
        #if DEBUG
        print("[{\(method)}url: \(url)]\n[parameters]: \(parameters)")
        #endif
        return Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers)
    }
    
    /// upload
    func upload(
        _ url: URLConvertible,
        img: UIImage,
        parameters: Parameters? = nil,
        headers: HTTPHeaders? = nil,
        closure: @escaping Request.ProgressHandler)
        -> SignalProducer<Any, NSError>
    {
        
        let data = UIImagePNGRepresentation(img)!
        #if DEBUG
            print("[{Upload image}url: \(url)]\n[parameters]: \(parameters)")
        #endif
        let signal = SignalProducer<(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?), NSError> { observer, disposable in
            
            #if DEBUG
            #endif
            Alamofire.upload(multipartFormData: { multipartFormData in
                    multipartFormData.append(data, withName: "file", fileName: "file", mimeType: multipartFormData.contentType)
                    guard let params = parameters else { return }
                    for (key, value) in params {
                        multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                        
                    }
                },
                to: url,
                encodingCompletion: { encodingResult in
                    switch encodingResult{
                    case .failure(let err):
                        observer.send(error: err as NSError)
                    case .success(let v):
                        observer.send(value: v)
                        observer.sendCompleted()
                    }
            })
        }
        return signal.flatMap(.latest, transform: { (request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) -> SignalProducer<Any, NSError> in
            return request.uploadProgress(closure: closure).reactive.responseJSON()
        })
    }
}



